import hashlib
import random
from config.database import DB
from app.models.AdminConfig import AdminConfig
from masonite.facades import (Cache, Session, Config)


class MyModelTrait:

    @classmethod
    def generate_login_session(cls, admin_user):
        """
        写入登录信息
        @param admin_user:
        @return:
        """
        # 写入登录态这里的 key 需要加上项目前缀
        key = cls.generate_cache_key(admin_user['id'])
        token = cls.generate_token(str(admin_user['id']))
        data = {
            'id': admin_user['id'],
            'account': admin_user['account'],
            'nickname': admin_user['nickname'],
            'admin_role_id': admin_user['admin_role_id'],
            'token': token
        }
        Session.set('admin_user', data)

        # 屏幕水印
        admin_config = AdminConfig.get_config()
        Session.set('watermark_switch', admin_config['watermark_switch'])

        # 还需要将登录态存入缓存 30 天, 30 * 86400 = 2592000
        Cache.put(key, token, seconds=2592000)

    @staticmethod
    def generate_password(password, salt):
        """
        生成密码
        @param string password: 密码
        @param string salt: 加密盐
        @return: string
        """
        obj = hashlib.sha256()
        password += salt
        obj.update(password.encode("utf-8"))

        return obj.hexdigest()

    @staticmethod
    def generate_salt(length=6, mode="string"):
        """
        @param integer length: 长度
        @param string  mode: 类型
        @return: string
        """
        string = "qwertyuiopasdfghjklzxcvbnm1234567890QWERTYUIOPASDFGHJKLZXCVBNM"
        integer = "0123456789"

        str2 = ""
        i = 0
        str1 = string
        if mode == "int":
            str1 = integer

        while i < length:
            str2 += str1[random.randint(0, len(str1) - 1)]
            i += 1
        return str2

    @staticmethod
    def search_for_show(table, where, column='*', page=1, limit=10, order="id DESC"):
        if not isinstance(page, int):
            page = int(page)
        if not isinstance(limit, int):
            limit = int(limit)

        if 1 > page:
            page = 1
        if 1 > limit:
            limit = 10

        offset = page * limit - limit
        if 0 > offset:
            offset = 0

        where = where.strip(" AND")
        where = where.strip(" OR")
        sql = "SELECT {0} FROM {1} ".format(column, table)
        if len(where) > 1:
            sql += 'WHERE ' + where
        sql += " ORDER BY {0}".format(order)
        sql += " LIMIT {0},{1}".format(offset, limit)
        # print(sql)
        result = DB.statement(sql)
        # print(result)
        """
        <class 'list'>
        result = [{column: value}, {column: value}]
        """

        sql = "SELECT COUNT(id) AS total FROM {0} ".format(table)
        if len(where) > 1:
            sql += 'WHERE ' + where
        # print(sql)
        result2 = DB.statement(sql)
        # print(result2)
        # print(result2[0]['total'])
        """
        <class 'list'>
        [{'total': 49}]
        """

        return result2[0]['total'], result

    @classmethod
    def generate_cache_key(cls, admin_user_id):
        """
        获取缓存 key
        @param admin_user_id:
        @return:
        """
        return "{0}admin_user_{1}".format(Config.get('application.app_name'), admin_user_id)

    @classmethod
    def generate_token(cls, admin_user_id):
        """
        生成 token
        @param admin_user_id:
        @return:
        """
        return cls.generate_password(cls.generate_salt(32), admin_user_id)